<template>
    <baseView>
        <div class="routeTrack">
            <div class="left-box">
                <DataTable :tableColumn="tableColumn" @paginChange="onPaginChange" :paginOption="paginOption"
                    :total="total" :tableData="tableData" :size="[10,20]" ref="tableRef">
                    <!-- 查询 -->
                    <template #search>
                        <div class="form-box">
                            <el-form :inline="true">
                                <el-form-item label="路线选择">
                                    <routeSelect v-model:selectValue="params.routeid"> </routeSelect>
                                </el-form-item>
                                <el-form-item label="日期">
                                    <el-date-picker v-model="params.date" type="date" style="width: 150px;"
                                        value-format="YYYY-MM-DD" :clearabel="false" />
                                </el-form-item>
                                <el-form-item label="时间段">
                                    <el-select v-model="params.time" placeholder="请选择" style="width: 100px;">
                                        <el-option v-for="item in timeOptions" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="垃圾类型">
                                        <el-select v-model="params.type" placeholder="请选择" style="width: 120px;"
                                            clearable>
                                            <el-option v-for="item in rubbishOption" :key="item.value"
                                                :label="item.text" :value="item.value" />
                                        </el-select>
                                    </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="search">
                                        <el-icon style="margin-right: 2px;">
                                            <Search />
                                        </el-icon>查询
                                    </el-button>
                                    <!-- <el-button type="primary" plain>重置</el-button> -->
                                </el-form-item>
                            </el-form>
                        </div>
                    </template>
                    <!-- 重量 -->
                    <template #重量="{ row }">
                        {{ row['实际桶数'] }} 桶 {{ row['实际重量'] }} kg
                    </template>
                    <template #status="{ row }">
                        <cleanTag :row="row"/>
                    </template>
                </DataTable>
            </div>
            <div class="right-box">
                <div class="mapView">
                    <mapContainer v-if="showMap" @mapReady="mapReady"></mapContainer>
                    <!-- 图例 -->
                    <div class="legendBox">
                        <div class="legend-item" v-for="(item, index) in tabList" :key="item.id">
                            <img :src="item.imgUrl" alt="" :class="[index == 0 ? 'img1' : 'img2']" /> <span>{{ item.name
                                }}</span>
                        </div>
                    </div>
                    <div class="mapTool" v-if="trackMap.trackCar">
                        <el-button type="primary" @click="doOperation('开始')"> 播放</el-button>
                        <!-- <el-button type="primary" @click="doOperation('重置')"> 重置</el-button> -->
                    </div>
                </div>
            </div>
        </div>
    </baseView>
</template>

<script setup>
import { vehicleGps, vehicleHistory } from "@/api/cleanRoute"
import dakaLegend from "@/assets/images/dakalegend.png"
import car from "@/assets/images/commonCar.png"
import close from "@/assets/images/close.png"
import carTrack from "@/assets/images/carTrack.png"
import daka from "@/assets/images/daka.png"
import dayjs from "dayjs"
import { cleanByRoute } from "@/api/cleanRoute"
import { onMounted } from "vue";


const showMap = ref(false)
let mapIns = null
function mapReady(map) {
    mapIns = map
    nextTick(() => {
        createTrack()
    })
}
const tableColumn = ref([
    {
        label: '商铺名',
        prop: '店铺名',
    },
    {
        label: '清运时间',
        prop: 'realtime',
    },
    {
        label: '清运状态',
        prop: 'status',
        slot: true
    },
    {
        label: "垃圾类型",
        prop: 'type',
    },
    {
        label: "清运数量",
        prop: '重量',
        slot: true,
    },
    {
        label: '作业人员',
        prop: "worker",
    },
])
const params = reactive({
    routeid: "",
    time: "am",
    date: dayjs(new Date()).format("YYYY-MM-DD"),
})
const paginOption = reactive({
    pagenum: 1,
    pagesize: 10
})
const total = ref(0)
const tableData = ref([])
const tableRef = ref(null)
function getCleanByRoute() {
    cleanByRoute(Object.assign(params, paginOption)).then(res => {
        if (res.code == 200) {
            tableData.value = res.data.list
            total.value = res.data.total
            showMap.value = true
            tableRef.value.computedHeight()
        }
    })
}
function onPaginChange({ type, size }) {
    paginOption[type] = size
    getCleanByRoute()

}
function search() {
    if(trackMap.isRunning) {
        doOperation("重置")
    }
    mapIns.clearMap()
    paginOption.pagenum = 1
    getCleanByRoute()
    createTrack()
}


const timeOptions = [
    {
        id: 1,
        label: '上午',
        value: "am"
    },
    {
        id: 2,
        label: '下午',
        value: "pm"
    }
]

let tabList = [
    {
        id: 1,
        name: '收运车',
        imgUrl: carTrack
    },
    {
        id: 2,
        name: '打卡位置',
        imgUrl: dakaLegend
    },
]


// 轨迹的实体集合
const trackMap = reactive({
    lineMap: [],  //轨迹点位的数组
    polyline: null, //轨迹实体
    passedPolyline: null, //车子行驶的轨迹实体
    trackCar: null, //行驶车子的实体
    isRunning: false   //是否正在行驶
})
// 创建路线,并且调用点位创建
function createTrack() {
    let dateRange = {
        plate: '沪ABL7815',
        datefrom: "",
        dateto: ""
    }
    // 判断上午下午 轨迹路线的时间段区间
    if (params.time == 'am') {
        dateRange.datefrom = dayjs(params.date).startOf('date').format("YYYY-MM-DD  HH:mm:ss")
        dateRange.dateto = dayjs(params.date).startOf('date').add(12, 'hour').format("YYYY-MM-DD  HH:mm:ss")
    } else if (params.time == 'pm') {
        dateRange.datefrom = dayjs(params.date).startOf('date').add(12, 'hour').format("YYYY-MM-DD  HH:mm:ss")
        dateRange.dateto = dayjs(params.date).endOf('date').format("YYYY-MM-DD  HH:mm:ss")
    }
    vehicleHistory(dateRange).then((res) => {
        if (res.code == 200) {
            if (res.data.length > 0) {
                //1. 整合这个时间段所有经纬度集合
                trackMap.lineMap = res.data.map((item) => {
                    return [item.lon, item.lat]
                })
                // 2.根据轨迹数组创建轨迹路线
                trackMap.polyline = new AMap.Polyline({
                    path: trackMap.lineMap,
                    showDir: true,
                    strokeColor: "#28F",  //线颜色
                    strokeWeight: 6,      //线宽
                });
                trackMap.passedPolyline = new AMap.Polyline({
                    strokeColor: "#AF5",  //线颜色
                    strokeWeight: 6,      //线宽
                });
                // 3.添加到地图中
                mapIns.add(trackMap.polyline)
                mapIns.add(trackMap.passedPolyline)
                mapIns.setFitView([trackMap.polyline])
                //4.创建行驶车辆,取第一个点作为起始位置,并且添加到地图中
                const [lng, lat] = trackMap.lineMap[0]
                trackMap.trackCar = new AMap.Marker({
                    position: new AMap.LngLat(lng, lat),
                    // label: {
                    //     content: item.name,
                    //     direction: 'bottom'
                    // },
                    // 将一张图片的地址设置为 icon
                    icon: new AMap.Icon({
                        size: [13, 26],
                        image: carTrack,
                        imageSize: [13, 26]
                    }),
                    // 这个一定要添加，方式缩放的时候点位偏移，x表示图片宽度的一半 y表示图片的高，整体取负值
                    offset: new AMap.Pixel(-7, -13),
                })
                mapIns.add(trackMap.trackCar)
                // 5.添加点击事件和移动
                trackMap.trackCar.on('moving', (e) => {
                    trackMap.passedPolyline.setPath(e.passedPath);
                })
                // 6.添加清运点位
                nextTick(() => {
                    createCleanedPoint()
                })
            } else {
                ElMessage.error('当前时间暂无轨迹数据');
            }

        }
    })
}
// 控制车子做动作
function doOperation(type) {
    switch (type) {
        case '开始':
            trackMap.isRunning = true
            trackMap.trackCar.moveAlong(trackMap.lineMap, {
                // 每一段的时长
                duration: 500,//可根据实际采集时间间隔设置
                // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
                autoRotation: true,
            });
            break;
        case '重置':
            if (trackMap.trackCar) {
                trackMap.trackCar.pauseMove()
                // mapIns.remove(currentTack.value)
                // mapIns.clearMap();
                // currentTack.value = null
            }
            break;
        default:
            break;
    }
}
const isFirst = ref(true)
// 清运点位的集合
const cleanedMap = ref([])
// 创建清运点位
function createCleanedPoint() {
    if (cleanedMap.value.length > 0) {
        for (let point of cleanedMap.value) {
            mapIns.remove(point)
        }
    }
    nextTick(() => {
        if (tableData.value.length > 0) {
            console.log("🚀 ~ nextTick ~ tableData.value.length:", tableData.value.length)
            //1.遍历已清运点位
            tableData.value.forEach((item) => {
                let marker = new AMap.Marker({
                    map: mapIns,
                    position: [item.lon, item.lat],
                    icon: new AMap.Icon({
                        size: [30, 35],
                        image: daka,
                        imageSize: [30, 35]
                    }),
                    // 这个一定要添加，方式缩放的时候点位偏移，x表示图片宽度的一半 y表示图片的高，整体取负值
                    offset: new AMap.Pixel(-15, -35)
                });
                cleanedMap.value.push(marker)
                marker.on('click', (e) => {
                    createInfoDakaWindow(item).open(mapIns, marker.getPosition())
                    // 给弹框的关闭按钮添加点击事件，关闭弹窗
                    document.getElementById('info-close').onclick = () => {
                        closeWindow()
                    }
                })
            })
                console.log("🚀 ~ tableData.value.forEach ~ cleanedMap.value:", cleanedMap.value)
        }
        isFirst.value = false
    })


}
watch(() => tableData.value, () => {
    nextTick(() => {
        createCleanedPoint()
    })
})
// 关闭弹框
function closeWindow() {
    let dom = document.getElementById('info-window')
    if (dom) {
        dom.remove()
    }
}
function createInfoDakaWindow(item) {
    let info = {
        垃圾类别: item.type,
        收运数量: item['实际桶数'] + '桶' + item['实际重量'] + 'kg',
        收运时间: item.realtime,
        收运人员: item.worker,
        收运坐标: item.lon + ',' + item.lat
    }
    let contentStr = ""
    for (let key in info) {
        contentStr += ` <div class="basic-info"> <span class="label"> ${key}: <span class="value">${info[key]}</span>  <span/> </div>`
    }
    //   <img src="${markerInfo}" /> 
    let infoBox =
        `
      <div class="info-wrap" id="info-window">
            <div class="info-title"> 
                <div class="title-wrap">
                    <div class="title">${item['店铺名']}</div>
                    <div class="icon" id="info-close">
                        <img src="${close}" /> 
                    </div>    
                </div>
            </div>
            <div class="content" style="width:280px">
                ${contentStr}
            </div>
           
      </div>
    `
    return new AMap.InfoWindow({
        isCustom: true,
        content: infoBox,
        offset: [0, -45]
    })
}
const rubbishOption = [
    {
        text: "干垃圾",
        value: "dry"
    },
    {
        text: "湿垃圾",
        value: "wet"
    },
    {
        text: "餐厨垃圾",
        value: "food"
    }
]
onMounted(() => {
    getCleanByRoute()
})


</script>

<style scoped>
.el-form--inline .el-form-item {
    margin-right: 15px;
}
</style>
<style lang="scss" scoped>
.form-box {
    display: flex;
    justify-content: flex-end;
}

.routeTrack {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;

    .left-box {
        width: 59%;
    }

    .right-box {
        width: 39%;
        .mapView {
            position: relative;
            height: 100%;
            width: 100%;


            .legendBox {
                background: #fff;
                border-radius: 10px;
                padding: 10px;
                position: absolute;
                top: 20px;
                left: 20px;
                z-index: 10;

                .legend-item {
                    display: flex;
                    align-items: center;
                    // justify-content: space-between;
                    // font-size: 26px;
                    color: rgba(51, 51, 51, 1);
                    margin-bottom: 10px;

                    .img1 {
                        width: 20px;
                        // height: 15px;
                    }

                    .img2 {
                        width: 30px;
                        height: 30px;
                    }

                    span {
                        margin-top: 5px;
                    }
                }
            }

            .mapTool {
                background: #fff;
                border-radius: 10px;
                padding: 10px;
                position: absolute;
                top: 20px;
                right: 20px;
                z-index: 10;
            }

        }
    }
}

.point-img {
    cursor: pointer;
}

.base-box {
    width: 54px;
    height: 28px;
    border-radius: 4px;
    margin: 0 auto;
}

.noClean {
    color: rgba(255, 255, 255, 1);
    background: rgba(197, 207, 224, 1);
}

.cleaning {
    color: rgba(36, 211, 255, 1);
    background: rgba(36, 211, 255, 0.2);
}

.cleaned {
    color: rgba(14, 204, 90, 1);
    background: rgba(208, 243, 222, 1);
}
</style>

<style>
.info-wrap {
    position: relative;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 4px;
    overflow: hidden;
}

.info-wrap>.info-title {
    height: 44px;
    background: linear-gradient(180deg, rgba(156, 224, 255, 0.95) 0%, rgba(255, 255, 255, 0.95) 100%), rgba(255, 255, 255, 1);
}

.info-wrap>.info-title>.title-wrap {
    display: flex;
    align-items: center;
    width: 100%;
    height: 100%;

    justify-content: space-between;
    padding: 0 14px;
    box-sizing: border-box;
    font-weight: bold;

}

.info-title>.title {
    color: rgba(51, 51, 51, 1);
}

.info-title>.title-wrap>.icon {
    cursor: pointer;
}

.info-title>.title-wrap>.icon img {
    width: 12px;
    height: 12px;
}

.info-wrap>.line {
    margin: 15px 0;
    width: 100%;
    height: 1px;
    background: rgba(239, 239, 239, 1);
}

.basic-info {
    margin: 5px 15px;
}

.basic-info .label {
    color: rgba(128, 128, 128, 1);
}

.basic-info .value {
    color: rgba(51, 51, 51, 1);
}

.amap-info-contentContainer {
    position: relative;
}

.info-arrow {
    position: absolute;
    bottom: -30px;
    left: 50%;
    transform: translateX(-50%);

}

.info-arrow>img {
    width: 30px;
    height: 18px;
}

.amap-marker-label {
    border: unset;
    background: unset;
}
</style>